package cn.edu.thu.tsqualitylite.controller.fanDataProblem;

import cn.edu.thu.tsquality.core.common.datasource.CsvDataSource;
import cn.edu.thu.tsquality.core.common.datasource.IDataSource;
import cn.edu.thu.tsqualitylite.common.constant.Algorithms;
import cn.edu.thu.tsqualitylite.common.constant.Constants;
import cn.edu.thu.tsqualitylite.common.util.ServerTable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

@Controller
public class InaccurateLRController
{

    @RequestMapping(value = "/api/fan-data-problem/inaccurate-LR", method = RequestMethod.POST)
    @ResponseBody
    public ServerTable runAlgorithm(
            @RequestBody Map<String, Object> params
    ) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException
    {
        String inputFilename = params.get("inputFilename").toString();
        if (!inputFilename.startsWith("/") && inputFilename.charAt(1) != ':') {
            inputFilename = Constants.FAN_DETECTION_PATH + inputFilename;
        }
        String outputFilename = params.get("outputFilename").toString();
        if (!outputFilename.startsWith("/") && outputFilename.charAt(1) != ':') {
            outputFilename = Constants.FAN_REPAIR_PATH + outputFilename;
        }

        // System.out.println("got params:"+params);

        Class algorithm = Algorithms.getAlgorithm("fan-data-problem-lr");
        Method method = algorithm.getMethod("main", String[].class);
        String[] args = new String[]{inputFilename, outputFilename};
        method.invoke(null, (Object) args);
        IDataSource dataSource = new CsvDataSource(outputFilename);
        return new ServerTable(dataSource.read());
    }

}
